<template>
  <div class="doctor-message">
    <h2>个人信息管理</h2>
    
    <el-form 
      :model="doctorForm" 
      :rules="rules"
      ref="formRef"
      label-width="100px"
      class="doctor-form"
    >
      <!-- 头像上传 -->
      <el-form-item label="头像" class="avatar-item">
        <el-upload
          class="avatar-uploader"
          :action="''"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleAvatarChange"
          :before-upload="beforeAvatarUpload"
        >
          <img 
            v-if="doctorForm.avatar" 
            :src="doctorForm.avatar" 
            class="avatar" 
            alt="头像"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <!-- 基本信息 -->
      <div class="form-section">
        <h3>基本信息</h3>
        <el-form-item label="账号">
          <span class="info-text">{{ doctorForm.doctorid }}</span>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="doctorForm.email" placeholder="请输入邮箱">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="doctorForm.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="doctorForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input-number 
            v-model="doctorForm.age" 
            :min="1" 
            :max="120"
            controls-position="right"
          />
        </el-form-item>

        <!-- 擅长方向 -->
        <el-form-item label="擅长方向" prop="skills">
          <el-radio-group
            v-model="doctorForm.skills"
            style="width: 100%"
          >
            <el-radio
              v-for="item in skillOptions"
              :key="item.value"
              :value="item.value"
              class="skill-radio"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!-- 基本信息更新按钮 -->
      <div class="form-actions">
        <el-button type="primary" @click="updateBasicInfo">更新基本信息</el-button>
      </div>

      <!-- 密码修改部分 -->
      <div class="form-section">
        <h3>修改密码</h3>
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="doctorForm.oldPassword" 
            type="password" 
            :show-password="true"
            placeholder="请输入原密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="doctorForm.newPassword" 
            type="password" 
            :show-password="true"
            placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="doctorForm.confirmPassword" 
            type="password" 
            :show-password="true"
            placeholder="请再次输入新密码"
          />
        </el-form-item>
        
        <!-- 密码修改按钮 -->
        <div class="form-actions">
          <el-button type="warning" @click="updatePassword" :disabled="!canUpdatePassword">
            修改密码
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Message } from '@element-plus/icons-vue'
import { updateDoctorInfo, uploadDoctorAvatar } from '../../api/doctor'

const formRef = ref<FormInstance>()

// 擅长方向选项
const skillOptions = [
  { label: '情感困扰', value: 'emotion' },
  { label: '学业压力', value: 'study' },
  { label: '职场压力', value: 'work' },
  { label: '家庭关系', value: 'family' },
  { label: '人际关系', value: 'social' },
  { label: '心理障碍', value: 'disorder' },
  { label: '抑郁症', value: 'depression' },
  { label: '焦虑症', value: 'anxiety' },
  { label: '强迫症', value: 'ocd' },
  { label: '失眠', value: 'insomnia' },
  { label: '青少年心理', value: 'youth' },
  { label: '婚恋咨询', value: 'marriage' }
]

// 表单数据
const doctorForm = ref({
  doctorid: Number(localStorage.getItem('doctorid') || '0'),
  name: localStorage.getItem('name') || '',
  sex: Number(localStorage.getItem('sex') || '0'),
  age: Number(localStorage.getItem('age') || '0'),
  email: localStorage.getItem('email') || '',
  skills: localStorage.getItem('skills') || '',
  avatar: localStorage.getItem('avatar') || '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 在组件挂载时确保数据已经正确初始化
onMounted(() => {
  const doctorid = localStorage.getItem('doctorid')
  if (doctorid) {
    doctorForm.value.doctorid = Number(doctorid)
  }
})

// 判断是否可以更新密码
const canUpdatePassword = computed(() => {
  return doctorForm.value.oldPassword && 
    doctorForm.value.newPassword && 
    doctorForm.value.confirmPassword && 
    doctorForm.value.newPassword === doctorForm.value.confirmPassword
})

// 头像上传前的验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('头像必须是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像选择变化的处理
const handleAvatarChange = async (file: any) => {
  if (!file) return
  
  try {
    const res = await uploadDoctorAvatar(doctorForm.value.doctorid, file.raw)
    
    if (res.code === '200') {
      // 处理返回的 base64 图片数据
      if (res.data.img) {
        const imageUrl = `data:image/jpeg;base64,${res.data.img}`
        doctorForm.value.avatar = imageUrl
        localStorage.setItem('avatar', imageUrl)
      }
      ElMessage.success('头像更新成功')
    } else {
      ElMessage.error(res.msg || '头像更新失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '头像更新失败')
  }
}

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄必须在1-120岁之间', trigger: 'blur' }
  ],
  skills: [
    { required: true, message: '请选择擅长方向', trigger: 'change' }
  ],
  oldPassword: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== doctorForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 更新基本信息
const updateBasicInfo = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const updateData = {
          doctorid: doctorForm.value.doctorid,
          name: doctorForm.value.name,
          sex: doctorForm.value.sex,
          age: doctorForm.value.age,
          email: doctorForm.value.email,
          skills: doctorForm.value.skills,
          password: '',
          oldPassword: ''
        }
        
        const res = await updateDoctorInfo(updateData)
        if (res.code === '200') {
          ElMessage.success('基本信息更新成功')
          // 更新本地存储
          localStorage.setItem('name', doctorForm.value.name)
          localStorage.setItem('sex', String(doctorForm.value.sex))
          localStorage.setItem('age', String(doctorForm.value.age))
          localStorage.setItem('email', doctorForm.value.email)
          localStorage.setItem('skills', doctorForm.value.skills)
        }
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败')
      }
    }
  })
}

// 更新密码
const updatePassword = async () => {
  if (!formRef.value) return
  
  await formRef.value.validateField(['oldPassword', 'newPassword', 'confirmPassword'], async (valid: boolean) => {
    if (valid) {
      try {
        const updateData = {
          doctorid: doctorForm.value.doctorid,
          name: doctorForm.value.name,
          sex: doctorForm.value.sex,
          age: doctorForm.value.age,
          email: doctorForm.value.email,
          skills: doctorForm.value.skills,
          password: doctorForm.value.newPassword,
          oldPassword: doctorForm.value.oldPassword
        }
        
        const res = await updateDoctorInfo(updateData)
        if (res.code === '200') {
          ElMessage.success('密码修改成功')
          // 清空密码字段
          doctorForm.value.oldPassword = ''
          doctorForm.value.newPassword = ''
          doctorForm.value.confirmPassword = ''
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error('密码修改失败')
      }
    }
  })
}
</script>

<style scoped>
.doctor-message {
  padding: 20px;
}

h2 {
  margin: 0 0 30px;
  font-size: 24px;
  color: #2c3e50;
}

.doctor-form {
  max-width: 600px;
}

.info-text {
  color: #606266;
}

.professional-section,
.password-section {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.professional-section h3,
.password-section h3 {
  margin: 0 0 20px;
  font-size: 18px;
  color: #2c3e50;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

:deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 100%;
}

:deep(.el-upload:hover) {
  border-color: #409EFF;
}

.avatar-item :deep(.el-form-item__content) {
  justify-content: flex-start;
}

.skill-radio {
  margin-right: 20px;
  margin-bottom: 10px;
}
</style>